package cn.jsu.oj.dispatchServer.satellite.factory;

import cn.jsu.oj.dispatchServer.satellite.annotation.HandlerType;
import cn.jsu.oj.dispatchServer.satellite.handler.Handler;
import cn.jsu.oj.dispatchServer.satellite.util.AnnScanUtil;
import cn.jsu.oj.dispatchServer.satellite.util.SpringUtil;
import cn.jsu.oj.dispatchServer.satellite.util.StringUtil;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理器工厂
 *
 * @author shan
 * @date 2022/06/29
 */
public class HandlerFactory implements Factory {

    /**
     * 处理器map
     */
    private Map<Short, Handler> handlerMap;

    /**
     * 处理器工厂构建
     */
    @Override
    public void build() {
        this.handlerMap = new ConcurrentHashMap<>(10);
        List<Class<?>> classList = AnnScanUtil.scanPackage("cn", HandlerType.class);
        for (Class<?> clazz : classList) {
            Short typeNo = clazz.getAnnotation(HandlerType.class).typeNo();
            String[] strings = clazz.getName().split("\\.");
            String beanName = StringUtil.initialFormat(strings[strings.length - 1], false);
            if (SpringUtil.getBean(beanName) == null) {
                SpringUtil.registerBean(beanName, clazz, false);
            }
            this.handlerMap.put(typeNo, (Handler) SpringUtil.getBean(beanName));
        }
    }

    /**
     * 获取处理器
     *
     * @param goodsNo 处理器编号
     * @return {@link Object }
     */
    @Override
    public Object getProduct(Short goodsNo) {
        return handlerMap.get(goodsNo);
    }
}
